package com.hfb.mashibing.alip8.juc.c020;


import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * Phaser-阶段:(控制某些线程在某些阶段执行)
 *   一般用不到，用在遗传算法中
 */

public class T08_TestPhaser {
    static Random rand = new Random();
    static Phaser phaser = new MarriagePhaser();

    public void millisleep(int millis) {
        try {
            TimeUnit.MILLISECONDS.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        phaser.bulkRegister(6);
        for (int i = 0; i < 6; i++) {
            final int nameIndex = i;
            new Thread(() ->{
                Person p = new Person("person " + nameIndex);
                p.arrive();
                phaser.arriveAndAwaitAdvance();

                p.eat();
                phaser.arriveAndAwaitAdvance();

                p.leave();
                phaser.arriveAndAwaitAdvance();
            }).start();
        }
    }

    static class MarriagePhaser extends Phaser {
        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            switch (phase) {
                case 0:
                    System.out.println("所有人到到齐了");
                    return false;
                case 1:
                    System.out.println("所有人吃完了");
                    return false;
                case 2:
                    System.out.println("所有人离开了");
                    System.out.println("婚礼结束！");
                    return true;
                default:
                    return true;
            }
        }
    }

    private static class Person {
        private String name;
        public Person(String name) {
            this.name = name;
        }

        public void arrive() {
            System.out.println(name + " 到到了");
        }

        public void eat() {
            System.out.println(name + " 吃完了");
        }

        public void leave() {
            System.out.println(name + " 离开了");
        }
    }
}
